<template>
  <div
    :id="id"
    :style="{ width: width + 'px', height: height + 'px', margin: '34px auto' }"
    class="m-map"
    :class="{map_absolute:flag}"
  />
</template>

<script>
export default {
  props: {
    width: {
      type: Number,
      default: 300
    },
    height: {
      type: Number,
      default: 300
    },
    point: {
      type: Array,
      default () {
        return [116.46, 39.92]
      }
    },
    flag: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      id: 'map',
      key: 'd7619ae73099aac4cd8bc732d73b5a8d'
    }
  },
  watch: {
    point (val, old) {
      this.map.setCenter(val)
      this.marker.setPosition(val)
    }
  },
  mounted () {
    const self = this
    self.id = `map${Math.random()
      .toString()
      .slice(4, 6)}`

    window.onmaploaded = () => {
      const map = new window.AMap.Map(self.id, {
        // resizeEnable: true,
        zoom: 16,
        center: self.point,
        viewMode: '3D' // 使用3D视图
      })
      // 实时路况图层
      const trafficLayer = new window.AMap.TileLayer.Traffic({
        zIndex: 10
      })
      map.add(trafficLayer)// 添加图层到地图
      self.map = map
      window.AMap.plugin('AMap.ToolBar', () => {
        const toolbar = new window.AMap.ToolBar()
        map.addControl(toolbar)
        const marker = new window.AMap.Marker({
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          position: self.point
        })
        self.marker = marker
        marker.setMap(map)
      })
    }
    const url = `https://webapi.amap.com/maps?v=1.4.10&key=${self.key}&callback=onmaploaded`
    const jsapi = document.createElement('script')
    jsapi.charset = 'utf-8'
    jsapi.src = url
    document.head.appendChild(jsapi)
  }
}
</script>

<style lang="scss">
.m-map {
  border: 1px solid #E5E5E5;
  border-radius: 8px;
  margin: 57px 8px!important;
}
.map_absolute {
    position: fixed!important;
    top: -57px;
    right: 205px!important;
    box-shadow:0 16px 18px #ccc;
}
</style>
